# Import various libraries
import os, sys, re, getopt, flatten
from CFG_parser import CFG

# Usage of program: use -h

# Handles command line arguments
def main(argv): 
  cfg = CFG()
  try:
    opt, args = getopt.getopt(argv, "hi:t:c:s:w:e", ["help", "write=", "train=", "cfg=", "interface=", "sentence=", "empirical"])
  except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
  output = None
  verbose = False
  for o, a in opt:
    if o in ("-h", "--help"):
      usage()
      sys.exit()
    elif o in ("-t", "--train"):
      print "Training on", str(a)
      cfg.trainonfile(a)
    elif o in ("-w", "--write"):
      print "Writing to file", str(a)
      cfg.writedict(a)
    elif o in ("-c", "--cfg"):
      print "Using trained CFG", str(a)
      cfg.readdict(a)
    elif o in ("-i", "--interface"):
      print "Starting interface for tree generation with verbose level",a
      Continue = True
      while(Continue):
        utter = raw_input("Type a sentence:\n")
        print flatten.flatten(cfg.CYKparse(str(utter),a))
        test = raw_input("Do you want to continue? (type n if not)\n")
        if test=='n': 
          Continue = False
          print "Thank you for supplying the sentences"
    elif o in ("-e", "--empirical"):
      print "Top production for VP, S, NP, SBAR, PP:"
      print "VP:",   sorted(cfg.CFG['VP'],   key=lambda production: production[1], reverse=True)[0:4]
      print "S:",    sorted(cfg.CFG['S' ],   key=lambda production: production[1], reverse=True)[0:4]
      print "NP:",   sorted(cfg.CFG['NP'],   key=lambda production: production[1], reverse=True)[0:4]
      print "SBAR:", sorted(cfg.CFG['SBAR'], key=lambda production: production[1], reverse=True)[0:4]
      print "PP:",   sorted(cfg.CFG['PP'],   key=lambda production: production[1], reverse=True)[0:4]
      
      print "\nFour words and their probabilities:"
      word1 = "peace"
      word2 = "love"
      word3 = "understand"
      word4 = "respect"
      for nonterm in cfg.term[word1]:
        print nonterm, "->", word1, ":", cfg.CFGprob[nonterm][str([word1])]
      for nonterm in cfg.term[word2]:
        print nonterm, "->", word2, ":", cfg.CFGprob[nonterm][str([word2])]
      for nonterm in cfg.term[word3]:
        print nonterm, "->", word3, ":", cfg.CFGprob[nonterm][str([word3])]
      for nonterm in cfg.term[word4]:
        print nonterm, "->", word4, ":", cfg.CFGprob[nonterm][str([word4])]
    
    
    
    
    elif o in ("-s", "--sentence"):
      print "Test sentences", str(a)
      f = open(a,'r')
      f2 = open('producedtrees', 'w')
      sentences = f.readlines()
      counter = 0
      for sentence in sentences:
        print "Tried sentences", counter
        counter+=1
        tree = cfg.CYKparse(str(sentence), 0)
        print tree
        f2.write(flatten.flatten(tree))
        f2.write("\n")
    elif o in ("-g", "--gold"):
      print "Testing on gold standard", str(a)
    elif o in ("-c", "--cfg"):
      print "Using trained CFG", str(a)


    else:
      assert False, "unhandled option"

def usage():
    usage = """
    -h --help       Prints this
    -t --train      Trains the CFG on the specified file
    -w --write      Writes CFG to specified file
    -c --cfg        Uses file to parse trained cfg
    -i --interface  Starts interface to generate trees from user input
    -s --sentence   Specify sentences to test on
    -e --empirical  Get Empirical data from the CFG
    """
    print usage



if __name__ == "__main__":
    main(sys.argv[1:]) # [1:] slices off the first argument which is the name of the program






